﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;
using System.Diagnostics;
using System.Xml;

namespace Handrise.CDCable.Update
{
    public partial class FrmUpdate : Form
    {
        private int zipFileLen = 0;
        private string serverVersion = "";

        public FrmUpdate(string zipFileLenStr, string serverVersionStr)
        {
            InitializeComponent();

            zipFileLen = int.Parse(zipFileLenStr);

            serverVersion = serverVersionStr;
        }

        private void delayTimer_Tick(object sender, EventArgs e)
        {
            delayTimer.Enabled =false ;

            string zipFileName = GetLocalPath() + "\\Update\\update.udd";
            int allSize = 0;

            using (FileStream stream = new FileStream(zipFileName,FileMode.Open))
            {
                ZipInputStream zipstream = new ZipInputStream(stream);
                ZipEntry entry = zipstream.GetNextEntry();

                //创建备份目录
                string bakDirctory = GetLocalPath() + "\\Update\\Bak" + DateTime.Now.ToString("yyyyMMdd");
                Directory.CreateDirectory(bakDirctory);

                while (entry != null)
                {
                    try
                    {
                        if (entry.IsFile)
                        {
                            //是文件
                            int readlength;
                            byte[] buff = new byte[1024 * 100];
                            string targetFile = GetLocalPath() + "\\" + entry.Name.Replace('/','\\');

                            //清除只读属性
                            if (File.Exists(targetFile))
                            {

                                FileInfo fi = new FileInfo(targetFile);

                                if (fi.Attributes.ToString().IndexOf("ReadOnly") != -1)
                                {

                                    fi.Attributes = FileAttributes.Normal;
                                }

                                

                            } 


                            ////备份文件
                            //string fileName = System.IO.Path.GetFileName(targetFile);
                            //if(File.Exists(targetFile))
                            //{
                            //    try
                            //    {
                            //        File.Copy(targetFile, bakDirctory + "\\" + fileName, true);
                            //        //删除原文件
                            //        File.Delete(targetFile);

                            //    }
                            //    catch (Exception ex)
                            //    {

                            //    }
                            //}


                            using (FileStream outputStream = new FileStream(targetFile,FileMode.Create))
                            {
                                while (true)
                                {
                                    readlength = zipstream.Read(buff, 0, buff.Length);

                                    if (readlength <= 0)
                                    {
                                        break;
                                    }

                                    outputStream.Seek(0, SeekOrigin.End);
                                    outputStream.Write(buff, 0, readlength);

                                }
                            }
                        }

                        if (entry.IsDirectory)
                        {
                            //是目录
                            string targetDirectory = GetLocalPath() + "\\" + entry.Name.Replace('/','\\');
                            if (!Directory.Exists(targetDirectory))
                            {
                                Directory.CreateDirectory(targetDirectory);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        //try
                        //{               
                        //    //还原备份的文件
                        //    string targetFile = GetLocalPath() + "\\" + entry.Name.Replace('/', '\\');
                        //    string fileName = System.IO.Path.GetFileName(targetFile);

                        //    File.Copy(bakDirctory + "\\" + fileName, targetFile, true);
                        //}
                        //catch (Exception ex1)
                        //{

                        //}
                    }

                    //显示进度
                    allSize += (int)entry.CompressedSize;
                    int percent = allSize*100/zipFileLen;
                    lbUpdate.Text = "系统更新中..." + percent + "%";
                    if (percent > 100)
                        percent = 100;
                    pbUpdateProcess.Value = percent;

                    Refresh();

                    entry = zipstream.GetNextEntry();
                }
            }

            lbUpdate.Text = "更新完成，开始启动新程序";

            Refresh();

            SetValue("Configuration/SystemInfo", "Version", serverVersion);

            //下载完成，关闭程序，并启动更新程序
            Process.Start(GetLocalPath() + "\\Handrise.CDCable.Mobile.UI.exe", "");

            Application.Exit();


        }

        public string GetLocalPath()
        {
            string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);

            if (path.StartsWith("file:\\"))
                return path.Remove(0, 6);
            else
                return path;
        }

        /// <summary>
        /// 设置单一项的值
        /// </summary>
        /// <param name="nodePath"></param>
        /// <param name="attributeName"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public bool SetValue(string nodePath, string attributeName, string value)
        {
            try
            {
                XmlDocument xmlDoc = new XmlDocument();

                xmlDoc.Load(GetLocalPath() + "\\AppConfig.xml");

                XmlNode xmlNode = xmlDoc.SelectSingleNode(nodePath);

                if (xmlNode != null)
                {

                    try
                    {
                        xmlNode.Attributes[attributeName].Value = value;
                    }
                    catch
                    {
                    }

                }

                xmlDoc.Save(GetLocalPath() + "\\AppConfig.xml");
                return true;
            }
            catch (Exception e)
            {
                return false;
            }

        }

    }
}